﻿Imports System.Globalization

Partial Public Class frmFollow_Payin
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "PAYMENT "
            LoadDataPayment("")
        End If
    End Sub

    Private Sub LoadDataPayment(ByVal Customer As String)
        Dim dtTemp As DataTable = clsGet.GetCustomerPayinManual(Customer)
        'จะได้รายชื่อมา
        Dim dt As DataTable = dtTemp.Clone
        dt.Columns.Add("TypePay", GetType(String))
        dt.AcceptChanges()
        dt.Rows.Clear()
        dt.AcceptChanges()
        For Each dr As DataRow In dtTemp.Rows
            If (clsGet.GetPayinAdvance(dr.Item("Booking_no"), dr.Item("Owner_Product"))) Then
                'ยังไม่ได้ทำการจ่ายเงิน
                Dim dnew As DataRow = dt.NewRow
                dnew.Item("Owner_Product") = dr.Item("Owner_Product")
                dnew.Item("Customer_Name") = dr.Item("Customer_Name")
                dnew.Item("Booking_no") = dr.Item("Booking_no")
                dnew.Item("Vehicle_Text") = dr.Item("Vehicle_Text")
                dnew.Item("Booking_Date") = dr.Item("Booking_Date")
                dnew.Item("Booking_Time") = dr.Item("Booking_Time")
                dnew.Item("TypePay") = "Cash Sale"
                dt.Rows.Add(dnew)
                dt.AcceptChanges()
            End If
        Next
        ViewState("Payment") = dt
        gridpayment.DataSource = dt
        gridpayment.DataBind()
        If (dt.Rows.Count = 0) Then
            lbAlert.Visible = True
            lbAlert.Text = "ไม่พบรายการที่ลูกค้า ค้างชำระ"
        Else
            lbAlert.Visible = False
        End If
    End Sub

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim CurrentIndex As Integer = gridpayment.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridpayment.PageIndex = 0
            Case "prev"
                If (gridpayment.PageIndex <> 0) Then
                    gridpayment.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridpayment.PageIndex <> gridpayment.PageCount) Then
                    gridpayment.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridpayment.PageIndex = gridpayment.PageCount
        End Select
        gridpayment.DataSource = ViewState("Payment")
        gridpayment.DataBind()
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim Page As GridViewRow = gridpayment.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridpayment.PageIndex = ddlPage.SelectedIndex
        gridpayment.DataSource = ViewState("Payment")
        gridpayment.DataBind()
    End Sub

    Private Sub gridpayment_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridpayment.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridpayment.PageIndex <> 0) Then
            Index = Index Mod (gridpayment.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            Session("PayinBooking") = gridpayment.DataKeys(Index).Values("Booking_no") & "$" & gridpayment.DataKeys(Index).Values("Owner_Product")
            Session("MAGENT_NAME_BULK") = gridpayment.DataKeys(Index).Values("Owner_Product") & " - " & gridpayment.DataKeys(Index).Values("Customer_Name") & ""
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_iframePayin').src = '../FormPopup/E-PayManual.aspx';", True)
            ModalPopupExtender7.Show()
        End If
    End Sub

    Private Sub gridpayment_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridpayment.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim dt As DataTable = clsGet.Get_MatFor_Sale_Order(gridpayment.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridpayment.DataKeys(e.Row.RowIndex).Values("Owner_Product"))
            Dim Vat As String = ""
            Dim dsConfig As DataSet = Session("Config")
            If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
                Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
            Else
                Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
            End If
            e.Row.Cells(3).Text = Gen_Body(Vat, dt)
        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridpayment.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridpayment.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridpayment.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridpayment.PageCount.ToString()
            End If
        End If
    End Sub

    Private Function Gen_Body(ByVal Vat As String, ByVal DSItem As DataTable) As String
        Dim HTML As String = ""
        Dim Value As Double = 0
        Dim ValueVat As Double = 0
        Dim WHT As Double = 0
        Dim row As Integer = 2
        For Each dr As DataRow In DSItem.Rows
            Value = Value + CDbl(dr.Item("data4"))
            Dim dt As DataTable = clsGet.Get_MeterailWhithodingTax(dr.Item("MATERIAL"))
            If (dt.Rows(0).Item("MAT_WHT") & "" = "01") Or (dt.Rows(0).Item("MAT_WHT") & "" = "02") Or (dt.Rows(0).Item("MAT_WHT") & "" = "03") Then
                '1%
                WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
            ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "04") Or (dt.Rows(0).Item("MAT_WHT") & "" = "05") Then
                '3%
                WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
            ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "06") Or (dt.Rows(0).Item("MAT_WHT") & "" = "22") Then
                '5%
                WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
            End If

        Next

        ValueVat = ((Value * CDbl(Vat)) / 100).ToString("############.00")
        Return FormatNumber(((CDbl(Value) + CDbl(ValueVat)) - CDbl(WHT)).ToString("#############0.00"), 2)
    End Function


    Private Sub gridpayment_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridpayment.RowEditing

    End Sub

    Private Sub btnLoadPayin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoadPayin.Click
        LoadDataPayment("")
    End Sub

    Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtCustomer.Text = String.Empty
    End Sub

    Private Sub radioPay_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioPay.SelectedIndexChanged
        If (radioPay.SelectedValue = "CH") Then
            rowCH.Visible = True
        Else
            rowCH.Visible = False
        End If
    End Sub

    Private Sub ddlBankOX_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBankOX.SelectedIndexChanged
        If ddlBankOX.SelectedValue = "0" Then
            ddlGL_Account.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
            ddlGL_Account.Items(0).Value = "0"
        Else
            Dim ds As DataTable = clsGet.Get_GL(ddlBankOX.SelectedValue, "")
            If (ds.Rows.Count > 0) Then
                With ddlGL_Account
                    .ClearSelection()
                    .Items.Clear()
                    .DataTextField = "Gl_Name"
                    .DataValueField = "Gl_Account"
                    .DataSource = ds
                    .DataBind()
                    .Items.Insert(0, "<--กรุณาเลือก GL Account-->")
                    .Items(0).Value = "0"
                End With
            End If

        End If
    End Sub

    Private Sub ddlBankDS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBankDS.SelectedIndexChanged
        If ddlBankDS.SelectedValue = "0" Then
            ddlGL_Account.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
            ddlGL_Account.Items(0).Value = "0"
        Else
            Dim ds As DataTable = clsGet.Get_GL(ddlBankDS.SelectedValue, "")
            If (ds.Rows.Count > 0) Then
                With ddlGL_AccountDS
                    .ClearSelection()
                    .Items.Clear()
                    .DataTextField = "Gl_Name"
                    .DataValueField = "Gl_Account"
                    .DataSource = ds
                    .DataBind()
                    .Items.Insert(0, "<--กรุณาเลือก GL Account-->")
                    .Items(0).Value = "0"
                End With
            End If

        End If
    End Sub

    Private Sub radioPayDS_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioPayDS.SelectedIndexChanged
        If (radioPayDS.SelectedValue = "CH") Then
            rowDS.Visible = True
        Else
            rowDS.Visible = False
        End If
    End Sub

    Private Sub btnPayOX_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPayOX.Click
        If (txtDate.Text.Trim = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการวันที่ชำระเงิน ');", True)
            Exit Sub
        End If
        ViewState("EX_BELNR") = ""
        Dim dt As DataTable = dt_Clearing()
        ViewState("ALLOC_NMBR") = ""
        Dim First As Boolean = True
        Dim Item_Text As String = ""
        Dim Gl_Account As String = ddlGL_Account.SelectedValue
        Dim DatePay As String = txtDate.Text
        Dim Ship_Name As String = ""
        Dim Booking_no As String = ""
        Dim Conditon As Boolean = True
        Dim CountText As String = ""
        Dim Count As Integer = 0
        For i As Integer = 0 To gridCNDN.Rows.Count - 1
            Dim chkCNDN As CheckBox = CType(gridCNDN.Rows(i).FindControl("chkCNDN"), CheckBox)
            If chkCNDN.Checked Then
                Dim ch As Boolean = True
                For k As Integer = 0 To CountText.Split(",").Count - 1
                    If (gridCNDN.DataKeys(i).Values("BILL_TO") = CountText.Split(",")(k)) Then
                        ch = False
                        Exit For
                    End If
                Next
                If (ch) Then
                    Count += 1
                    If (CountText = "") Then
                        CountText = gridCNDN.DataKeys(i).Values("BILL_TO")
                    Else
                        CountText &= "," & gridCNDN.DataKeys(i).Values("BILL_TO")
                    End If

                End If
            End If
        Next
        For L As Integer = 0 To Count - 1
            dt = dt_Clearing()
            For i As Integer = 0 To gridCNDN.Rows.Count - 1
                Dim chkCNDN As CheckBox = CType(gridCNDN.Rows(i).FindControl("chkCNDN"), CheckBox)
                If chkCNDN.Checked Then
                    Ship_Name = ""
                    Booking_no = gridCNDN.DataKeys(i).Values("Booking_no")
                    ViewState("ALLOC_NMBR") = gridCNDN.DataKeys(i).Values("ALLOC_NMBR")
                    Dim dr As DataRow = dt.NewRow

                    dr.Item("Bukrs") = gridCNDN.DataKeys(i).Values("BUKRS")
                    dr.Item("Gjahr") = gridCNDN.DataKeys(i).Values("GJAHR")
                    dr.Item("Belnr") = gridCNDN.DataKeys(i).Values("BELNR")
                    dr.Item("Blart") = gridCNDN.DataKeys(i).Values("BLART")
                    dr.Item("Waers") = gridCNDN.DataKeys(i).Values("WAERS")
                    dr.Item("Whtamt") = gridCNDN.DataKeys(i).Values("WHTAMT")
                    dr.Item("Netamt") = gridCNDN.DataKeys(i).Values("NETAMT")
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            Next
            If (radioPay.SelectedValue = "CH") Then
                If (txtCH.Text.Trim() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุรายละเอียดของเช็ค ');", True)
                    Exit Sub
                End If
                Item_Text = "CH " & txtCH.Text
            Else
                Item_Text = "TR " & ddlBankOX.SelectedValue
            End If
            Conditon = inCOMEpayment(dt, Ship_Name, Item_Text, Booking_no, Gl_Account, DatePay)
            If Not (Conditon) Then
                Exit For
            End If
        Next

        If (Conditon) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ชำระเงินเรียบร้อย ');", True)
            Dim EX_B As String = ""
            For i As Integer = 0 To ViewState("EX_BELNR").ToString.Split(",").Count - 1
                If (ViewState("EX_BELNR").ToString.Split(",")(i) & "" <> "") Then
                    If (EX_B = "") Then
                        EX_B = ViewState("EX_BELNR").ToString.Split(",")(i)
                    Else
                        EX_B &= Environment.NewLine & ViewState("EX_BELNR").ToString.Split(",")(i)
                    End If
                End If
            Next
            lbRV.Text = EX_B
            PanelPayOX.Visible = False
            PanelRVOX.Visible = True
            ViewState("EX_BELNR") = ""
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการชำระเงิน ');", True)
        End If
    End Sub

    Private Sub btnPayDS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPayDS.Click
        If (txtDateDS.Text.Trim = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการวันที่ชำระเงิน ');", True)
            Exit Sub
        End If
        Dim dt As DataTable = dt_Clearing()
        ViewState("ALLOC_NMBR") = ""
        Dim First As Boolean = True
        Dim Item_Text As String = ""
        Dim Gl_Account As String = ddlGL_AccountDS.SelectedValue
        Dim DatePay As String = txtDateDS.Text
        Dim Ship_Name As String = ""
        Dim Booking_no As String = ""
        Dim Conditon As Boolean = True
        Dim CountText As String = ""
        Dim Count As Integer = 0
        For i As Integer = 0 To gridDefferred.Rows.Count - 1
            Dim chkCNDN As CheckBox = CType(gridDefferred.Rows(i).FindControl("chkCNDN"), CheckBox)
            If chkCNDN.Checked Then
                Dim ch As Boolean = True
                For k As Integer = 0 To CountText.Split(",").Count - 1
                    If (gridDefferred.DataKeys(i).Values("BILL_TO") = CountText.Split(",")(k)) Then
                        ch = False
                        Exit For
                    End If
                Next
                If (ch) Then
                    Count += 1
                    If (CountText = "") Then
                        CountText = gridDefferred.DataKeys(i).Values("BILL_TO")
                    Else
                        CountText &= "," & gridDefferred.DataKeys(i).Values("BILL_TO")
                    End If

                End If
            End If
        Next
        For L As Integer = 0 To Count - 1
            dt = dt_Clearing()
            For i As Integer = 0 To gridDefferred.Rows.Count - 1
                Dim chkCNDN As CheckBox = CType(gridDefferred.Rows(i).FindControl("chkCNDN"), CheckBox)
                If chkCNDN.Checked Then
                    Ship_Name = ""
                    Booking_no = gridDefferred.DataKeys(i).Values("Booking_no")
                    ViewState("ALLOC_NMBR") = gridDefferred.DataKeys(i).Values("ALLOC_NMBR")
                    Dim dr As DataRow = dt.NewRow

                    dr.Item("Bukrs") = gridDefferred.DataKeys(i).Values("BUKRS")
                    dr.Item("Gjahr") = gridDefferred.DataKeys(i).Values("GJAHR")
                    dr.Item("Belnr") = gridDefferred.DataKeys(i).Values("BELNR")
                    dr.Item("Blart") = gridDefferred.DataKeys(i).Values("BLART")
                    dr.Item("Waers") = gridDefferred.DataKeys(i).Values("WAERS")
                    dr.Item("Whtamt") = gridDefferred.DataKeys(i).Values("WHTAMT")
                    dr.Item("Netamt") = gridDefferred.DataKeys(i).Values("NETAMT")
                    dt.Rows.Add(dr)
                    dt.AcceptChanges()
                End If
            Next
            If (radioPayDS.SelectedValue = "CH") Then
                If (txtDS.Text.Trim() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุรายละเอียดของเช็ค ');", True)
                    Exit Sub
                End If
                Item_Text = "CH " & txtDS.Text
            Else
                Item_Text = "TR " & ddlBankDS.SelectedValue
            End If
            Conditon = inCOMEpayment(dt, Ship_Name, Item_Text, Booking_no, Gl_Account, DatePay)
            If Not (Conditon) Then
                Exit For
            End If
        Next

        If (Conditon) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ชำระเงินเรียบร้อย ');", True)
            Dim EX_B As String = ""
            For i As Integer = 0 To ViewState("EX_BELNR").ToString.Split(",").Count - 1
                If (ViewState("EX_BELNR").ToString.Split(",")(i) & "" <> "") Then
                    If (EX_B = "") Then
                        EX_B = ViewState("EX_BELNR").ToString.Split(",")(i)
                    Else
                        EX_B &= Environment.NewLine & ViewState("EX_BELNR").ToString.Split(",")(i)
                    End If
                End If
            Next
            lbRVDS.Text = EX_B
            PanelPayDS.Visible = False
            PanelRVDS.Visible = True
            ViewState("EX_BELNR") = ""
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการชำระเงิน ');", True)
        End If
        'For i As Integer = 0 To gridDefferred.Rows.Count - 1
        '    Dim chkCNDN As CheckBox = CType(gridDefferred.Rows(i).FindControl("chkCNDN"), CheckBox)
        '    If (chkCNDN.Checked) Then
        '        If (ViewState("ALLOC_NMBR") <> gridDefferred.DataKeys(i).Values("ALLOC_NMBR")) Then
        '            If Not (First) Then
        '                If (radioPay.SelectedValue = "CH") Then
        '                    If (txtCH.Text.Trim() = "") Then
        '                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุรายละเอียดของเช็ค ');", True)
        '                        Exit Sub
        '                    End If
        '                    Item_Text = "CH " & txtCH.Text
        '                Else
        '                    Item_Text = "TR " & ddlBankOX.SelectedValue
        '                End If
        '                Conditon = inCOMEpayment(dt, Ship_Name, Item_Text, Booking_no, Gl_Account, DatePay)
        '                If Not (Conditon) Then
        '                    Exit For
        '                End If
        '                dt = dt_Clearing()
        '            End If
        '            First = False
        '        End If
        '        ViewState("ALLOC_NMBR") = gridDefferred.DataKeys(i).Values("ALLOC_NMBR")
        '        Ship_Name = gridDefferred.DataKeys(i).Values("Ship_Name")
        '        Booking_no = gridDefferred.DataKeys(i).Values("Booking_no")

        '        Dim dr As DataRow = dt.NewRow

        '        dr.Item("Bukrs") = gridDefferred.DataKeys(i).Values("BUKRS")
        '        dr.Item("Gjahr") = gridDefferred.DataKeys(i).Values("GJAHR")
        '        dr.Item("Belnr") = gridDefferred.DataKeys(i).Values("BELNR")
        '        dr.Item("Blart") = gridDefferred.DataKeys(i).Values("BLART")
        '        dr.Item("Waers") = gridDefferred.DataKeys(i).Values("WAERS")
        '        dr.Item("Whtamt") = gridDefferred.DataKeys(i).Values("WHTAMT")
        '        dr.Item("Netamt") = gridDefferred.DataKeys(i).Values("NETAMT")
        '        dt.Rows.Add(dr)
        '        dt.AcceptChanges()
        '    End If
        'Next
        'If Conditon Then
        '    If (dt.Rows.Count > 0) Then
        '        If (radioPay.SelectedValue = "CH") Then
        '            If (txtCH.Text.Trim() = "") Then
        '                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุรายละเอียดของเช็ค ');", True)
        '                Exit Sub
        '            End If
        '            Item_Text = "CH " & txtCH.Text
        '        Else
        '            Item_Text = "TR " & ddlBankOX.SelectedValue
        '        End If
        '        Conditon = inCOMEpayment(dt, Ship_Name, Item_Text, Booking_no, Gl_Account, DatePay)
        '    End If

        'End If
        'If (Conditon) Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ชำระเงินเรียบร้อย ');", True)
        '    LoadCNDN(txtCustomerCNDN.Text)
        'Else
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการชำระเงิน ');", True)
        'End If
    End Sub
    Private Function dt_Clearing() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Bukrs", GetType(String))
        dt.Columns.Add("Gjahr", GetType(String))
        dt.Columns.Add("Belnr", GetType(String))
        dt.Columns.Add("Blart", GetType(String))
        dt.Columns.Add("Waers", GetType(String))
        dt.Columns.Add("Whtamt", GetType(String))
        dt.Columns.Add("Netamt", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Function inCOMEpayment(ByVal dt As DataTable, ByVal Vessel_Name As String, ByVal Bank As String, ByVal Booking_no As String, ByVal GL_Account As String, ByVal DatePay As String) As Boolean
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()

        Dim BABI_CLEARING As SAP_IPORT.ZBAPI_CLEARING
        Dim BABI_CLEARINGTB As New SAP_IPORT.ZBAPI_CLEARINGTable
        Dim sumAmount As Double = 0
        Dim Wht As Double = 0
        For Each dr As DataRow In dt.Rows
            BABI_CLEARING = New SAP_IPORT.ZBAPI_CLEARING
            BABI_CLEARING.Comp_Code = dr.Item("Bukrs")
            BABI_CLEARING.Fisc_Year = dr.Item("Gjahr")
            BABI_CLEARING.Ac_Doc_No = dr.Item("Belnr")
            BABI_CLEARING.Blart = dr.Item("Blart")
            BABI_CLEARING.Waers = dr.Item("Waers")
            BABI_CLEARING.Whtamt = dr.Item("Whtamt")
            BABI_CLEARINGTB.Insert(0, BABI_CLEARING)
            sumAmount += CDbl(dr.Item("Netamt"))
            Wht += CDbl(dr.Item("Whtamt"))
        Next
        If (sumAmount >= 0.0) Then
            Dim EX_BUKRS As String = ""
            Dim EX_BELNR As String = ""
            Dim EX_GJAHR As String = ""
            Dim IPORT_NUMBER As String = clsGet.Get_IportNumber()
            Dim CustomerCode As String = CInt(ViewState("Customer"))
            Dim ZBABI_BK As New SAP_IPORT.ZBAPI_BANK
            ZBABI_BK.Amount = sumAmount.ToString("##############.##")
            ZBABI_BK.Gl_Account = GL_Account
            ZBABI_BK.Item_Text = Bank
            If (radioPayDS.SelectedValue = "CH") Then
                ZBABI_BK.Value_Date = CDate(DatePay).AddDays(1).ToString("yyyyMMdd")
            Else
                ZBABI_BK.Value_Date = CDate(DatePay).ToString("yyyyMMdd")
            End If


            Dim ZBABI_HD As New SAP_IPORT.ZBAPI_HEADER
            ZBABI_HD.Bupla = "0000"
            ZBABI_HD.Doc_Date = CDate(DatePay).ToString("yyyyMMdd")
            ZBABI_HD.Header_Txt = ""
            ZBABI_HD.Pstng_Date = CDate(DatePay).ToString("yyyyMMdd")
            ' ZBABI_HD.Pstng_Date = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))
            Dim BABITable As New SAP_IPORT.BAPIRET1Table

            SAP_Data.Zbapi_Iport_Income_Payment(ZBABI_BK, CustomerCode, ZBABI_HD, IPORT_NUMBER, "X", EX_BELNR, EX_BUKRS, EX_GJAHR, BABI_CLEARINGTB, BABITable)
            For Each dm As SAP_IPORT.BAPIRET1 In BABITable
                Dim Meass As String = dm.Message
            Next
            If (EX_BUKRS <> "") And (EX_BELNR <> "") And (EX_GJAHR <> "") Then
                ViewState("EX_BELNR") &= "," & EX_BELNR
                Dim clsDB As New ClassDatabase()
                Dim clsFc As New ClassFunction()
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Application.Lock()
                conn.Open()
                tran = clsDB.BeginTran(conn)
                If (clsFc.InsertIportNumber(IPORT_NUMBER, conn, tran) > 0) Then
                    If (clsFc.InsertSAP_INCOME(Booking_no, IPORT_NUMBER, CustomerCode, ZBABI_HD.Doc_Date, ZBABI_HD.Pstng_Date, ZBABI_HD.Bupla, ZBABI_HD.Header_Txt, ZBABI_BK.Gl_Account, ZBABI_BK.Amount, ZBABI_BK.Value_Date, ZBABI_BK.Item_Text, EX_BUKRS, EX_BELNR, EX_GJAHR, Wht, "M", conn, tran) > 0) Then
                        For Each dr As SAP_IPORT.ZBAPI_CLEARING In BABI_CLEARINGTB
                            If (clsFc.InsertSAP_INCOME_CLEARING(IPORT_NUMBER, dr.Comp_Code, dr.Fisc_Year, dr.Ac_Doc_No, dr.Blart, dr.Whtamt, dr.Waers, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                    Else
                        condition = False
                    End If
                    'If (ViewState("ALLOC_NMBR") & "" <> "") Then
                    '    If (clsFc.UPDATESale_OrderPay(Booking_no, ViewState("ALLOC_NMBR"), EX_BUKRS, EX_BELNR, EX_GJAHR, conn, tran) < 1) Then
                    '        condition = False
                    '    End If
                    'End If

                End If


                For Each dm As SAP_IPORT.BAPIRET1 In BABITable
                    If (clsFc.InsertSAP_Table_MESSAGE(IPORT_NUMBER, "Zbapi_Iport_Income_Payment", dm.Type, dm.Id, dm.Number, dm.Message, dm.Log_No, dm.Log_Msg_No, dm.Message_V1, dm.Message_V2, dm.Message_V3, dm.Message_V4, conn, tran) < 1) Then
                        condition = False
                    End If
                Next

                If (condition) Then
                    clsDB.CommitTran(tran)
                    Return True

                Else
                    clsDB.RollBackTran(tran)
                    Return False

                End If
                ViewState("ALLOC_NMBR") = ""
                Application.UnLock()
                conn.Dispose()
            End If
            ClassSAP.SAP_CLOSE(SAP_Data)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ยอดชำระเงินไม่ถูกต้อง ');", True)
        End If

    End Function

    Private Sub LoadCNDN(ByVal CustomerCode As String)
        PanelPayOX.Visible = True
        PanelRVOX.Visible = False
        PanelPayDS.Visible = True
        PanelRVDS.Visible = False
        Dim ds As DataTable = clsGet.Get_Bank("")
        If (ds.Rows.Count > 0) Then
            With ddlBankOX
                .ClearSelection()
                .Items.Clear()
                .DataTextField = "Bank_Name"
                .DataValueField = "Bank_SAP"
                .DataSource = ds
                .DataBind()
                .Items.Insert(0, "<--กรุณาเลือกธนาคาร-->")
                .Items(0).Value = "0"
            End With
        End If
        ddlGL_Account.Items.Clear()
        ddlGL_Account.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
        ddlGL_Account.Items(0).Value = "0"

        ds = clsGet.Get_Bank("")
        If (ds.Rows.Count > 0) Then
            With ddlBankDS
                .ClearSelection()
                .Items.Clear()
                .DataTextField = "Bank_Name"
                .DataValueField = "Bank_SAP"
                .DataSource = ds
                .DataBind()
                .Items.Insert(0, "<--กรุณาเลือกธนาคาร-->")
                .Items(0).Value = "0"
            End With
        End If
        ddlGL_AccountDS.Items.Clear()
        ddlGL_AccountDS.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
        ddlGL_AccountDS.Items(0).Value = "0"

        Dim dtCus As DataTable = clsGet.Get_Customer(CustomerCode)
        If dtCus.Rows.Count > 0 Then
            lbName.Text = "ชื่อลูกค้า : " & CustomerCode & " - " & dtCus.Rows(0).Item("NAME1") & " " & dtCus.Rows(0).Item("NAME2") & " " & dtCus.Rows(0).Item("NAME3")
        Else
            lbName.Text = "ชื่อลูกค้า : " & CustomerCode
        End If
        Try
            CustomerCode = CInt(CustomerCode).ToString("0000000000")
        Catch ex As Exception

        End Try

        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()

        Dim CompanyCode As String = "1001"
        '  Dim CustomerCode As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no")
        Dim EX_SUBRC As String = "0"  'ถ้ามีค่าเป็น 0 คือพบข้อมูล
        Dim BABI_ARTABLE As New SAP_IPORT.ZBAPI_AR_OPENTable
        SAP_Data.Zbapi_Iport_Ar_Open_Item(CompanyCode, CustomerCode, EX_SUBRC, BABI_ARTABLE)
        Dim dt As DataTable = CreateTable()
        Dim dtDeferred As DataTable = CreateTable()
        If (EX_SUBRC = "0") Then
            For Each S As SAP_IPORT.ZBAPI_AR_OPEN In BABI_ARTABLE
                ' dt = addValue(dt, S)
                If (S.Blart = "R1") Or (S.Blart = "R5") Or (S.Blart = "R7") Then
                    If (S.Mwskz <> "") Then
                        If (S.Mwskz = "DS") Then
                            dtDeferred = addValue(dtDeferred, S)
                        Else
                            dt = addValue(dt, S)
                        End If
                    End If
                End If

            Next
        End If
        If (dt.Rows.Count = 0) Then
            lbAlertVat.Visible = True
            lbAlertVat.Text = "ไม่พบรายการ CN,DN"
            btnPayOX.Visible = False
        Else
            lbAlertVat.Visible = False
            btnPayOX.Visible = True

        End If
        If (dtDeferred.Rows.Count = 0) Then
            lbAlertDeferred.Visible = True
            lbAlertDeferred.Text = "ไม่พบรายการ CN,DN"
            btnPayDS.Visible = False
        Else
            lbAlertDeferred.Visible = False
            btnPayDS.Visible = True
        End If
        gridCNDN.DataSource = SetDate(dt)
        gridCNDN.DataBind()
        gridDefferred.DataSource = SetDate(dtDeferred)
        gridDefferred.DataBind()
        ClassSAP.SAP_CLOSE(SAP_Data)
    End Sub

    Public Function SetDate(ByVal dt As DataTable) As DataTable
        Dim Newdt As DataTable = CreateTable()
        Newdt.Columns.Add("Ship_Name", GetType(String))
        Newdt.Columns.Add("Booking_no", GetType(String))
        Newdt.AcceptChanges()
        For Each dr As DataRow In dt.Rows
            Dim dtBiiling As DataTable = clsGet.Get_VesselFrom_Billing(dr.Item("ALLOC_NMBR"))
            If (dtBiiling.Rows.Count = 1) Then
                Dim drNew As DataRow = Newdt.NewRow
                drNew.Item("BUKRS") = dr.Item("BUKRS")
                drNew.Item("BELNR") = dr.Item("BELNR")
                drNew.Item("GJAHR") = dr.Item("GJAHR")
                drNew.Item("BUZEI") = dr.Item("BUZEI")
                drNew.Item("BILL_TO") = dr.Item("BILL_TO")
                drNew.Item("MWSKZ") = dr.Item("MWSKZ")
                drNew.Item("BLART") = dr.Item("BLART")
                drNew.Item("DOC_DESC") = dr.Item("DOC_DESC")
                drNew.Item("XBLNR") = dr.Item("XBLNR")
                drNew.Item("ALLOC_NMBR") = dr.Item("ALLOC_NMBR")
                drNew.Item("BLDAT") = dr.Item("BLDAT")
                drNew.Item("DUEDT") = dr.Item("DUEDT")
                drNew.Item("WAERS") = dr.Item("WAERS")
                drNew.Item("BASMAT") = dr.Item("BASMAT")
                drNew.Item("VAT") = dr.Item("VAT")
                drNew.Item("NETAMT") = dr.Item("NETAMT")
                drNew.Item("WHTAMT") = dr.Item("WHTAMT")
                drNew.Item("TEXT40") = dr.Item("TEXT40")
                drNew.Item("REBZG") = dr.Item("REBZG")
                drNew.Item("REBZJ") = dr.Item("REBZJ")
                drNew.Item("REBZZ") = dr.Item("REBZZ")
                drNew.Item("Ship_Name") = dtBiiling.Rows(0).Item("Ship_Name") & ""
                drNew.Item("Booking_no") = dtBiiling.Rows(0).Item("Booking_no") & ""
                Newdt.Rows.Add(drNew)
                Newdt.AcceptChanges()
            End If
        Next

        Dim dsView As DataView = Newdt.DefaultView
        dsView.Sort = " Booking_no"
        Newdt = New DataTable
        Newdt = (clsGet.ConvertDataViewToDataSet(dsView).Copy)

        Dim Booking_no As String = ""
        Dim dataCNDN As DataTable = Newdt.Clone
        dataCNDN.Columns.Add("TYPE_DOC", GetType(String))
        dataCNDN.AcceptChanges()
        Dim BASE As Double = 0
        Dim VAT As Double = 0
        Dim NET As Double = 0
        Dim WHT As Double = 0
        Dim chkFirst As Boolean = True
        For i As Integer = 0 To Newdt.Rows.Count - 1
            Dim drNew As DataRow
            If (Newdt.Rows(i).Item("Booking_no") <> Booking_no) Then
                If Not (chkFirst) Then
                    drNew = dataCNDN.NewRow
                    drNew.Item("TYPE_DOC") = "Total(By Ship)"
                    drNew.Item("BUKRS") = ""
                    drNew.Item("BELNR") = ""
                    drNew.Item("GJAHR") = ""
                    drNew.Item("BUZEI") = ""
                    drNew.Item("BILL_TO") = ""
                    drNew.Item("MWSKZ") = ""
                    drNew.Item("BLART") = ""
                    drNew.Item("DOC_DESC") = ""
                    drNew.Item("XBLNR") = ""
                    drNew.Item("ALLOC_NMBR") = ""
                    drNew.Item("BLDAT") = ""
                    drNew.Item("DUEDT") = ""
                    drNew.Item("WAERS") = ""
                    drNew.Item("BASMAT") = FormatNumber(BASE, 2)
                    drNew.Item("VAT") = FormatNumber(VAT, 2)
                    drNew.Item("NETAMT") = FormatNumber(NET, 2)
                    drNew.Item("WHTAMT") = FormatNumber(WHT, 2)
                    drNew.Item("TEXT40") = ""
                    drNew.Item("REBZG") = ""
                    drNew.Item("REBZJ") = ""
                    drNew.Item("REBZZ") = ""
                    drNew.Item("Ship_Name") = "_F"
                    drNew.Item("Booking_no") = Newdt.Rows(i).Item("Booking_no") & ""
                    dataCNDN.Rows.Add(drNew)
                    dataCNDN.AcceptChanges()

                    drNew = dataCNDN.NewRow
                    drNew.Item("TYPE_DOC") = ""
                    drNew.Item("BUKRS") = ""
                    drNew.Item("BELNR") = ""
                    drNew.Item("GJAHR") = ""
                    drNew.Item("BUZEI") = ""
                    drNew.Item("BILL_TO") = ""
                    drNew.Item("MWSKZ") = ""
                    drNew.Item("BLART") = ""
                    drNew.Item("DOC_DESC") = ""
                    drNew.Item("XBLNR") = ""
                    drNew.Item("ALLOC_NMBR") = ""
                    drNew.Item("BLDAT") = ""
                    drNew.Item("DUEDT") = ""
                    drNew.Item("WAERS") = ""
                    drNew.Item("BASMAT") = ""
                    drNew.Item("VAT") = ""
                    drNew.Item("NETAMT") = ""
                    drNew.Item("WHTAMT") = ""
                    drNew.Item("TEXT40") = ""
                    drNew.Item("REBZG") = ""
                    drNew.Item("REBZJ") = ""
                    drNew.Item("REBZZ") = ""
                    drNew.Item("Ship_Name") = ""
                    drNew.Item("Booking_no") = ""
                    dataCNDN.Rows.Add(drNew)
                    dataCNDN.AcceptChanges()
                Else
                    chkFirst = False
                End If
                Booking_no = Newdt.Rows(i).Item("Booking_no")
                drNew = dataCNDN.NewRow
                drNew.Item("TYPE_DOC") = "เรือ : " & Newdt.Rows(i).Item("Ship_Name") & ""
                drNew.Item("BUKRS") = ""
                drNew.Item("BELNR") = ""
                drNew.Item("GJAHR") = ""
                drNew.Item("BUZEI") = ""
                drNew.Item("BILL_TO") = ""
                drNew.Item("MWSKZ") = ""
                drNew.Item("BLART") = ""
                drNew.Item("DOC_DESC") = ""
                drNew.Item("XBLNR") = ""
                drNew.Item("ALLOC_NMBR") = "Booking No. : " & Newdt.Rows(i).Item("Booking_no") & ""
                drNew.Item("BLDAT") = ""
                drNew.Item("DUEDT") = ""
                drNew.Item("WAERS") = ""
                drNew.Item("BASMAT") = ""
                drNew.Item("VAT") = ""
                drNew.Item("NETAMT") = ""
                drNew.Item("WHTAMT") = ""
                drNew.Item("TEXT40") = ""
                drNew.Item("REBZG") = ""
                drNew.Item("REBZJ") = ""
                drNew.Item("REBZZ") = ""
                drNew.Item("Ship_Name") = "_H"
                drNew.Item("Booking_no") = Newdt.Rows(i).Item("Booking_no") & ""
                dataCNDN.Rows.Add(drNew)
                dataCNDN.AcceptChanges()
            End If
            drNew = dataCNDN.NewRow
            drNew.Item("TYPE_DOC") = Newdt.Rows(i).Item("BLART") & " : " & Newdt.Rows(i).Item("DOC_DESC")
            drNew.Item("BUKRS") = Newdt.Rows(i).Item("BUKRS")
            drNew.Item("BELNR") = Newdt.Rows(i).Item("BELNR")
            drNew.Item("GJAHR") = Newdt.Rows(i).Item("GJAHR")
            drNew.Item("BUZEI") = Newdt.Rows(i).Item("BUZEI")
            drNew.Item("BILL_TO") = Newdt.Rows(i).Item("BILL_TO")
            drNew.Item("MWSKZ") = Newdt.Rows(i).Item("MWSKZ")
            drNew.Item("BLART") = Newdt.Rows(i).Item("BLART")
            drNew.Item("DOC_DESC") = Newdt.Rows(i).Item("DOC_DESC")
            drNew.Item("XBLNR") = Newdt.Rows(i).Item("XBLNR")
            drNew.Item("ALLOC_NMBR") = Newdt.Rows(i).Item("ALLOC_NMBR")
            drNew.Item("BLDAT") = Newdt.Rows(i).Item("BLDAT")
            drNew.Item("DUEDT") = Newdt.Rows(i).Item("DUEDT")
            drNew.Item("WAERS") = Newdt.Rows(i).Item("WAERS")
            drNew.Item("BASMAT") = Newdt.Rows(i).Item("BASMAT")
            drNew.Item("VAT") = Newdt.Rows(i).Item("VAT")
            drNew.Item("NETAMT") = Newdt.Rows(i).Item("NETAMT")
            drNew.Item("WHTAMT") = Newdt.Rows(i).Item("WHTAMT")
            drNew.Item("TEXT40") = Newdt.Rows(i).Item("TEXT40")
            drNew.Item("REBZG") = Newdt.Rows(i).Item("REBZG")
            drNew.Item("REBZJ") = Newdt.Rows(i).Item("REBZJ")
            drNew.Item("REBZZ") = Newdt.Rows(i).Item("REBZZ")
            drNew.Item("Ship_Name") = Newdt.Rows(i).Item("Ship_Name") & ""
            drNew.Item("Booking_no") = Newdt.Rows(i).Item("Booking_no") & ""
            Try
                BASE += CDbl(Newdt.Rows(i).Item("BASMAT"))
                VAT += CDbl(Newdt.Rows(i).Item("VAT"))
                NET += CDbl(Newdt.Rows(i).Item("NETAMT"))
                WHT += CDbl(Newdt.Rows(i).Item("WHTAMT"))
            Catch ex As Exception

            End Try
            dataCNDN.Rows.Add(drNew)
            dataCNDN.AcceptChanges()
        Next
        If (Newdt.Rows.Count > 0) Then
            Dim drNew As DataRow = dataCNDN.NewRow
            drNew.Item("TYPE_DOC") = "Total(By Ship)"
            drNew.Item("BUKRS") = ""
            drNew.Item("BELNR") = ""
            drNew.Item("GJAHR") = ""
            drNew.Item("BUZEI") = ""
            drNew.Item("BILL_TO") = ""
            drNew.Item("MWSKZ") = ""
            drNew.Item("BLART") = ""
            drNew.Item("DOC_DESC") = ""
            drNew.Item("XBLNR") = ""
            drNew.Item("ALLOC_NMBR") = ""
            drNew.Item("BLDAT") = ""
            drNew.Item("DUEDT") = ""
            drNew.Item("WAERS") = ""
            drNew.Item("BASMAT") = FormatNumber(BASE, 2)
            drNew.Item("VAT") = FormatNumber(VAT, 2)
            drNew.Item("NETAMT") = FormatNumber(NET, 2)
            drNew.Item("WHTAMT") = FormatNumber(WHT, 2)
            drNew.Item("TEXT40") = ""
            drNew.Item("REBZG") = ""
            drNew.Item("REBZJ") = ""
            drNew.Item("REBZZ") = ""
            drNew.Item("Ship_Name") = "_F"
            drNew.Item("Booking_no") = ""
            dataCNDN.Rows.Add(drNew)
            dataCNDN.AcceptChanges()

            drNew = dataCNDN.NewRow
            drNew.Item("TYPE_DOC") = ""
            drNew.Item("BUKRS") = ""
            drNew.Item("BELNR") = ""
            drNew.Item("GJAHR") = ""
            drNew.Item("BUZEI") = ""
            drNew.Item("BILL_TO") = ""
            drNew.Item("MWSKZ") = ""
            drNew.Item("BLART") = ""
            drNew.Item("DOC_DESC") = ""
            drNew.Item("XBLNR") = ""
            drNew.Item("ALLOC_NMBR") = ""
            drNew.Item("BLDAT") = ""
            drNew.Item("DUEDT") = ""
            drNew.Item("WAERS") = ""
            drNew.Item("BASMAT") = ""
            drNew.Item("VAT") = ""
            drNew.Item("NETAMT") = ""
            drNew.Item("WHTAMT") = ""
            drNew.Item("TEXT40") = ""
            drNew.Item("REBZG") = ""
            drNew.Item("REBZJ") = ""
            drNew.Item("REBZZ") = ""
            drNew.Item("Ship_Name") = ""
            drNew.Item("Booking_no") = ""
            dataCNDN.Rows.Add(drNew)
            dataCNDN.AcceptChanges()
        End If
        Return dataCNDN
    End Function

    Private Function CreateTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("BUKRS", GetType(String))  'Company Code
        dt.Columns.Add("BELNR", GetType(String))   'Accounting Document Number
        dt.Columns.Add("GJAHR", GetType(String))   'Fiscal Year
        dt.Columns.Add("BUZEI", GetType(String))   'Number of Line Item Within Accounting Document
        dt.Columns.Add("BILL_TO", GetType(String))   'Customer Number 1
        dt.Columns.Add("MWSKZ", GetType(String))    'Sales Tax Code
        dt.Columns.Add("BLART", GetType(String))    'Document Type
        dt.Columns.Add("DOC_DESC", GetType(String))   'Long Text
        dt.Columns.Add("XBLNR", GetType(String))   'Reference Document Number
        dt.Columns.Add("ALLOC_NMBR", GetType(String))   'Assignment Number
        dt.Columns.Add("BLDAT", GetType(String))   'Document Date in Document
        dt.Columns.Add("DUEDT", GetType(String))   'Due date
        dt.Columns.Add("WAERS", GetType(String))   'Currency Key
        dt.Columns.Add("BASMAT", GetType(String))  'Amount in Local Currency
        dt.Columns.Add("VAT", GetType(String))    'Tax Amount in Local Currency
        dt.Columns.Add("NETAMT", GetType(String))  'Amount in Local Currency
        dt.Columns.Add("WHTAMT", GetType(String))   'Withholding tax amount (in local currency)
        dt.Columns.Add("TEXT40", GetType(String))   'Text, 40 Characters Long
        dt.Columns.Add("REBZG", GetType(String))   'Number of the Invoice the Transaction Belongs to
        dt.Columns.Add("REBZJ", GetType(String))   'Fiscal Year of the Relevant Invoice (for Credit Memo)
        dt.Columns.Add("REBZZ", GetType(String))   'Line Item in the Relevant Invoice
        dt.AcceptChanges()
        Return dt
    End Function

    Private Function addValue(ByVal dt As DataTable, ByVal S As SAP_IPORT.ZBAPI_AR_OPEN) As DataTable
        Dim dr As DataRow = dt.NewRow
        dr.Item("BUKRS") = S.Bukrs  'Company Code
        dr.Item("BELNR") = S.Belnr  'Accounting Document Number
        dr.Item("GJAHR") = S.Gjahr 'Fiscal Year
        dr.Item("BUZEI") = S.Buzei   'Number of Line Item Within Accounting Document
        dr.Item("BILL_TO") = S.Bill_To  'Customer Number 1
        dr.Item("MWSKZ") = S.Mwskz    'Sales Tax Code
        dr.Item("BLART") = S.Blart   'Document Type
        dr.Item("DOC_DESC") = S.Doc_Desc   'Long Text
        dr.Item("XBLNR") = S.Xblnr  'Reference Document Number
        dr.Item("ALLOC_NMBR") = S.Alloc_Nmbr  'Assignment Number
        dr.Item("BLDAT") = S.Bldat   'Document Date in Document
        dr.Item("DUEDT") = S.Duedt   'Due date
        dr.Item("WAERS") = S.Waers  'Currency Key
        dr.Item("BASMAT") = S.Basmat  'Amount in Local Currency
        dr.Item("VAT") = S.Vat    'Tax Amount in Local Currency
        dr.Item("NETAMT") = S.Netamt 'Amount in Local Currency
        dr.Item("WHTAMT") = S.Whtamt  'Withholding tax amount (in local currency)
        dr.Item("TEXT40") = S.Text40   'Text, 40 Characters Long
        dr.Item("REBZG") = S.Rebzg  'Number of the Invoice the Transaction Belongs to
        dr.Item("REBZJ") = S.Rebzj   'Fiscal Year of the Relevant Invoice (for Credit Memo)
        dr.Item("REBZZ") = S.Rebzz  'Line Item in the Relevant Invoice
        dt.Rows.Add(dr)
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub TabPayment_ActiveTabChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabPayment.ActiveTabChanged
        If (TabPayment.ActiveTabIndex = 0) Then
            LoadDataPayment("")
        ElseIf (TabPayment.ActiveTabIndex = 1) Then
            LoadCNDN("")
        Else
            LoadPaymentRecord("")
        End If
    End Sub

    Private Sub BtnSearchCNDN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSearchCNDN.Click
        Dim dtCus As DataSet = clsGet.Get_CustomerMaster(txtCustomerCNDN.Text)
        If (dtCus.Tables(0).Rows.Count = 0) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลลูกค้า ');", True)
        ElseIf (dtCus.Tables(0).Rows.Count > 1) Then
            Session("txtCUSCNDN") = txtCustomerCNDN.Text
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_iframeCustomer').src = '../FormPopup/frm_FindCustomer_Popup.aspx';", True)
            ModalPopupExtender1.Show()
        Else
            LoadCNDN(txtCustomerCNDN.Text)
            ViewState("Customer") = txtCustomerCNDN.Text
        End If

    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        LoadDataPayment(txtCustomer.Text)
    End Sub

    Private Sub btnCusLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCusLoad.Click
        If ViewState("RECORD") & "" = "Y" Then
            LoadPaymentRecord(Session("Customer_NoCNDN") & "")
        Else
            LoadCNDN(Session("Customer_NoCNDN") & "")
        End If
        ViewState("Customer") = Session("Customer_NoCNDN")
        Session("Customer_NoCNDN") = Nothing
        ViewState("RECORD") = Nothing


    End Sub


    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub gridCNDN_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridCNDN.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Try
                e.Row.Cells(3).Text = CInt(e.Row.Cells(3).Text)
                Dim dt As DataTable = clsGet.Get_Customer(e.Row.Cells(3).Text)
                If (dt.Rows.Count > 0) Then
                    e.Row.Cells(3).ToolTip = dt.Rows(0).Item("NAME1") & " " & dt.Rows(0).Item("NAME2") & " " & dt.Rows(0).Item("NAME3")
                End If
            Catch ex As Exception

            End Try
            Dim chk As CheckBox = CType(e.Row.FindControl("chkCNDN"), CheckBox)
            If (gridCNDN.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "_H") Or (gridCNDN.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "_F") Then
                chk.Visible = False
            Else
                chk.Visible = True
                Dim DUE As String = gridCNDN.DataKeys(e.Row.RowIndex).Values("DUEDT") & ""
                Try
                    Dim days As String = DUE.Substring(6, 2)
                    Dim Month As String = GetNameMonth(DUE.Substring(4, 2))
                    Dim Year As String = DUE.Substring(0, 4)
                    DUE = days & " " & Month & " " & Year
                    If (CDate(DUE) > Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))) Then
                        Dim DayCurrent As String = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                        Dim Day As Integer = DateDiff(DateInterval.Day, CDate(DayCurrent), CDate(DUE))

                        e.Row.Cells(12).Text = "NOT DUE"
                        e.Row.Cells(13).Text = "-" & Day
                    ElseIf (CDate(DUE) < Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))) Then
                        Dim DayCurrent As String = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                        Dim Day As Integer = DateDiff(DateInterval.Day, CDate(DUE), CDate(DayCurrent))

                        e.Row.Cells(12).Text = "OVER DUE"
                        e.Row.Cells(13).Text = Day
                    Else
                        e.Row.Cells(12).Text = "DUE"
                        e.Row.Cells(13).Text = "0"
                    End If

                Catch ex As Exception

                End Try
            End If
            If (gridCNDN.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "") Then
                chk.Visible = False
                e.Row.BackColor = Drawing.Color.White
            End If
            Try
                e.Row.Cells(9).Text = FormatNumber(CDbl(e.Row.Cells(7).Text) + CDbl(e.Row.Cells(8).Text), 2)
            Catch ex As Exception

            End Try
        ElseIf (e.Row.RowType = DataControlRowType.Footer) Then
            e.Row.Cells(1).Text = "NET Amount"
            e.Row.Cells(7).Text = "0"
            e.Row.Cells(8).Text = "0"
            e.Row.Cells(9).Text = "0"
            e.Row.Cells(10).Text = "0"
            lbMoneyCNDN.Text = "0"
        End If
    End Sub

    Private Sub gridDefferred_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridDefferred.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Try
                e.Row.Cells(3).Text = CInt(e.Row.Cells(3).Text)
                Dim dt As DataTable = clsGet.Get_Customer(e.Row.Cells(3).Text)
                If (dt.Rows.Count > 0) Then
                    e.Row.Cells(3).ToolTip = dt.Rows(0).Item("NAME1") & " " & dt.Rows(0).Item("NAME2") & " " & dt.Rows(0).Item("NAME3")
                End If
            Catch ex As Exception

            End Try
            Dim chk As CheckBox = CType(e.Row.FindControl("chkCNDN"), CheckBox)
            If (gridDefferred.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "_H") Or (gridDefferred.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "_F") Then
                chk.Visible = False
            Else
                chk.Visible = True
                Dim DUE As String = gridDefferred.DataKeys(e.Row.RowIndex).Values("DUEDT") & ""
                Try
                    Dim days As String = DUE.Substring(6, 2)
                    Dim Month As String = GetNameMonth(DUE.Substring(4, 2))
                    Dim Year As String = DUE.Substring(0, 4)
                    DUE = days & " " & Month & " " & Year
                    If (CDate(DUE) > Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))) Then
                        Dim DayCurrent As String = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                        Dim Day As Integer = DateDiff(DateInterval.Day, CDate(DayCurrent), CDate(DUE))

                        e.Row.Cells(12).Text = "NOT DUE"
                        e.Row.Cells(13).Text = "-" & Day
                    ElseIf (CDate(DUE) < Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))) Then
                        Dim DayCurrent As String = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                        Dim Day As Integer = DateDiff(DateInterval.Day, CDate(DUE), CDate(DayCurrent))

                        e.Row.Cells(12).Text = "OVER DUE"
                        e.Row.Cells(13).Text = Day
                    Else
                        e.Row.Cells(12).Text = "DUE"
                        e.Row.Cells(13).Text = "0"
                    End If

                Catch ex As Exception

                End Try
            End If
            If (gridDefferred.DataKeys(e.Row.RowIndex).Values("Ship_Name") & "" = "") Then
                chk.Visible = False
                e.Row.BackColor = Drawing.Color.White
            End If
            Try
                e.Row.Cells(9).Text = FormatNumber(CDbl(e.Row.Cells(7).Text) + CDbl(e.Row.Cells(8).Text), 2)
            Catch ex As Exception

            End Try

        ElseIf (e.Row.RowType = DataControlRowType.Footer) Then
            e.Row.Cells(1).Text = "NET Amount"
            e.Row.Cells(7).Text = "0"
            e.Row.Cells(8).Text = "0"
            e.Row.Cells(9).Text = "0"
            e.Row.Cells(10).Text = "0"
            lbMoneyDeferred.Text = "0"
        End If
    End Sub
    Public Sub chkCNDN_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim BASE As Double = 0
        Dim VAT As Double = 0
        Dim NET As Double = 0
        Dim WHT As Double = 0
        For i As Integer = 0 To gridCNDN.Rows.Count - 1
            Dim chk As CheckBox = CType(gridCNDN.Rows(i).FindControl("chkCNDN"), CheckBox)
            If (chk.Checked) Then
                Try
                    BASE += CDbl(gridCNDN.Rows(i).Cells(7).Text)
                    VAT += CDbl(gridCNDN.Rows(i).Cells(8).Text)
                    NET += CDbl(gridCNDN.Rows(i).Cells(9).Text)
                    WHT += CDbl(gridCNDN.Rows(i).Cells(10).Text)
                Catch ex As Exception

                End Try
            End If
        Next
        gridCNDN.FooterRow.Cells(7).Text = FormatNumber(BASE, 2)
        gridCNDN.FooterRow.Cells(8).Text = FormatNumber(VAT, 2)
        gridCNDN.FooterRow.Cells(9).Text = FormatNumber(NET, 2)
        gridCNDN.FooterRow.Cells(10).Text = FormatNumber(WHT, 2)
        lbMoneyCNDN.Text = FormatNumber(NET - WHT, 2) & " บาท"
    End Sub

    Public Sub chkDefferred_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim BASE As Double = 0
        Dim VAT As Double = 0
        Dim NET As Double = 0
        Dim WHT As Double = 0
        For i As Integer = 0 To gridDefferred.Rows.Count - 1
            Dim chk As CheckBox = CType(gridDefferred.Rows(i).FindControl("chkCNDN"), CheckBox)
            If (chk.Checked) Then
                Try
                    BASE += CDbl(gridDefferred.Rows(i).Cells(7).Text)
                    VAT += CDbl(gridDefferred.Rows(i).Cells(8).Text)
                    NET += CDbl(gridDefferred.Rows(i).Cells(9).Text)
                    WHT += CDbl(gridDefferred.Rows(i).Cells(10).Text)
                Catch ex As Exception

                End Try
            End If
        Next
        gridDefferred.FooterRow.Cells(7).Text = FormatNumber(BASE, 2)
        gridDefferred.FooterRow.Cells(8).Text = FormatNumber(VAT, 2)
        gridDefferred.FooterRow.Cells(9).Text = FormatNumber(NET, 2)
        gridDefferred.FooterRow.Cells(10).Text = FormatNumber(WHT, 2)
        lbMoneyDeferred.Text = FormatNumber(NET - WHT, 2) & " บาท"
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub btnBackRVOX_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBackRVOX.Click
        Dim Cus As String = txtCustomerCNDN.Text
        If (Cus = "") Then
            Cus = ViewState("Customer")
        End If
        LoadCNDN(Cus)
    End Sub

    Private Sub btnBackRVDS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBackRVDS.Click
        Dim Cus As String = txtCustomerCNDN.Text
        If (Cus = "") Then
            Cus = ViewState("Customer")
        End If
        LoadCNDN(Cus)
    End Sub

    Private Sub btnRecord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRecord.Click
        Dim dtCus As DataSet = clsGet.Get_CustomerMaster(txtCustomerRecord.Text)
        If (dtCus.Tables(0).Rows.Count = 0) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลลูกค้า ');", True)
        ElseIf (dtCus.Tables(0).Rows.Count > 1) Then
            Session("txtCUSCNDN") = txtCustomerCNDN.Text
            ViewState("RECORD") = "Y"
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_iframeCustomer').src = '../FormPopup/frm_FindCustomer_Popup.aspx';", True)
            ModalPopupExtender1.Show()
        Else
            LoadCNDN(txtCustomerCNDN.Text)
            ViewState("Customer") = txtCustomerRecord.Text
        End If
    End Sub

    Private Sub LoadPaymentRecord(ByVal IM_CUSTOMER As String)
        Dim IM_COMPANY As String = "1001"
        Dim IM_DATE_FROM As String = Date.Now.ToString("yyyy", New CultureInfo("en-US")) & "0101"
        Dim IM_DATE_TO As String = Date.Now.ToString("yyyy", New CultureInfo("en-US")) & "1231"
        Dim EX_SUBRC As Integer = 0

        Dim ClassSAP As New Class_SAP
        Dim SAP_CLEAR As New SAP_IPORT.ZBAPI_AR_CLEARTable

        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        SAP_Data.Zbapi_Iport_Ar_Clear_Item(IM_COMPANY, IM_CUSTOMER, IM_DATE_FROM, IM_DATE_TO, EX_SUBRC, SAP_CLEAR)
        ClassSAP.SAP_CLOSE(SAP_Data)
        If (SAP_CLEAR.Count > 0) Then
            Dim dt As DataTable = CreatePaymentRecord()
            For Each dr As SAP_IPORT.ZBAPI_AR_CLEAR In SAP_CLEAR
                Dim dn As DataRow = dt.NewRow()
                dn.Item("BUKRS") = dr.Bukrs
                dn.Item("BELNR") = dr.Belnr
                dn.Item("GJAHR") = dr.Gjahr
                dn.Item("BUZEI") = dr.Buzei
                dn.Item("BILL_TO") = dr.Bill_To
                dn.Item("MWSKZ") = dr.Mwskz
                dn.Item("BLART") = dr.Blart
                dn.Item("DOC_DESC") = dr.Doc_Desc
                dn.Item("XBLNR") = dr.Xblnr
                dn.Item("BLDAT") = dr.Bldat
                dn.Item("DUEDT") = dr.Duedt
                dn.Item("WAERS") = dr.Waers
                dn.Item("BASMAT") = dr.Basmat
                dn.Item("VAT") = dr.Vat
                dn.Item("NETAMT") = dr.Netamt
                dn.Item("WHTAMT") = dr.Whtamt
                dn.Item("TEXT40") = dr.Text40
                dn.Item("CLEAR_DATE") = dr.Clear_Date
                dn.Item("CLR_DOC_NO") = dr.Clr_Doc_No
                dn.Item("ADV_YEAR") = dr.Adv_Year
                dn.Item("ADV_DOC_NO") = dr.Adv_Doc_No
                If (dr.Adv_Doc_No & "" = "") Then
                    dn.Item("ALLOC_NMBR") = dr.Clr_Doc_No
                Else
                    dn.Item("ALLOC_NMBR") = dr.Adv_Doc_No
                End If
                dt.Rows.Add(dn)
                dt.AcceptChanges()
            Next
            LabelAlertRecord.Visible = False
            ViewState("Record") = dt
            gridRecord.DataSource = dt
            gridRecord.DataBind()
        Else
            LabelAlertRecord.Visible = True
            LabelAlertRecord.Text = "ไม่พบประวัติรายการชำระเงิน"
        End If
    End Sub


    Private Function CreatePaymentRecord() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("BUKRS", GetType(String))
        dt.Columns.Add("BELNR", GetType(String))
        dt.Columns.Add("GJAHR", GetType(String))
        dt.Columns.Add("BUZEI", GetType(String))
        dt.Columns.Add("BILL_TO", GetType(String))
        dt.Columns.Add("MWSKZ", GetType(String))
        dt.Columns.Add("BLART", GetType(String))
        dt.Columns.Add("DOC_DESC", GetType(String))
        dt.Columns.Add("XBLNR", GetType(String))
        dt.Columns.Add("BLDAT", GetType(String))
        dt.Columns.Add("DUEDT", GetType(String))
        dt.Columns.Add("WAERS", GetType(String))
        dt.Columns.Add("BASMAT", GetType(String))
        dt.Columns.Add("VAT", GetType(String))
        dt.Columns.Add("NETAMT", GetType(String))
        dt.Columns.Add("WHTAMT", GetType(String))
        dt.Columns.Add("TEXT40", GetType(String))
        dt.Columns.Add("CLEAR_DATE", GetType(String))
        dt.Columns.Add("CLR_DOC_NO", GetType(String))
        dt.Columns.Add("ADV_YEAR", GetType(String))
        dt.Columns.Add("ADV_DOC_NO", GetType(String))
        dt.Columns.Add("ALLOC_NMBR", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub gridRecord_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridRecord.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Try
                e.Row.Cells(1).Text = CInt(e.Row.Cells(1).Text)
                Dim dt As DataTable = clsGet.Get_Customer(e.Row.Cells(1).Text)
                If (dt.Rows.Count > 0) Then
                    e.Row.Cells(1).ToolTip = dt.Rows(0).Item("NAME1") & " " & dt.Rows(0).Item("NAME2") & " " & dt.Rows(0).Item("NAME3")
                End If
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(8).Text = FormatNumber(CDbl(e.Row.Cells(6).Text) + CDbl(e.Row.Cells(7).Text), 2)
            Catch ex As Exception

            End Try
        End If
    End Sub
End Class